# coding: utf-8

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.cache import cache_page
import json

from ssdb.ssdb_cli import get_key
from api import search, detail, byclass
from public import banner, menu
from models import Health, Link, Details
from cache.ssdb_cache import ClassifiCation, like, recommended, Dailys, clear_cache
from cache.mysqls import Details_MySQL
# Create your views here.


@cache_page(86400)
def Index(request):

		"""
		首页
		:return:
		"""

		banner_data = banner()
		menu_data = menu()
		datas_recom = []
		datas_like = []

		for i in range(1,7):
				key = 'recommended_%s' %i
				recom = get_key(key=key)
				datas_recom.append(recom)

		for i in range(1, 15):
				key = 'like_%s' %i
				like = get_key(key)
				datas_like.append(like)

		return render(request, 'index.html', {
				'banner': banner_data,
				'menu': menu_data,
				'title': u'美食网，带给您不一样的味道！',
				'recommended': datas_recom,
				'like': datas_like,
		})


def Search(request):

		"""
		搜索页
		:return:
		"""

		banner_data = banner()
		menu_data = menu()
		title = u'美食网 | 搜索结果'

		if request.method == 'POST':
				name = request.POST.get('name')
				data = Details.objects.filter(name__contains=name)[0:20]
				if len(data) == 0:
					data = search(key=name, num=20)

		elif request.method == 'GET':
				name = request.GET.get('name')
				if name is None:
					return HttpResponseRedirect('/')
				data = Details.objects.filter(name__contains=name)[0:20]
				if len(data) == 0:
					data = search(key=name, num=20)

		return render(request, 'search.html', {
				'banner': banner_data,
				'menu': menu_data,
				'title': title,
				'data': data,
		})


@cache_page(86400)
def Food(request, classid, id):

		"""
		内容页
		:return:
		"""

		banner_data = banner()
		menu_data = menu()

		try:
				data = Details.objects.get(d_id=id)
				title = data.name
				data.material = json.loads(data.material)
				data.process = json.loads(data.process)
		except Exception:
				data = detail(id=id)
				Details_MySQL(detail(id=id))
				if data:
					title = data['name']
				else:
					title = 'error'

		return render(request, 'food.html', {
				'banner': banner_data,
				'menu': menu_data,
				'title': title,
				'data': data
		})


@cache_page(86400)
def Daily(request):

		"""
		家常菜谱
		:return:
		"""

		banner_data = banner()
		menu_data = menu()
		data = get_key('daily')

		for i in data['list']:
			try:
				Details.objects.get(d_id=i['id'])
			except Exception, e:
				Details_MySQL(i)

		return render(request, 'daily.html', {
				'banner': banner_data,
				'menu': menu_data,
				'title': u'美食网 | 家常菜谱',
				'data': data,
		})


@cache_page(86400)
def Classification(request, classid):

		"""
		分类查询
		:return:
		"""

		banner_data = banner()
		menu_data = menu()
		data = byclass(classid=classid, start=0, num=20)

		return render(request, 'classification.html', {
				'banner': banner_data,
				'menu': menu_data,
				'title': u'美食网 | 分类',
				'data': data,
		})


@cache_page(86400)
def Snacks(request):

		"""
		小吃大全
		:return:
		"""

		banner_data = banner()
		menu_data = menu()
		classid = get_key('snacks')[0]['classid']
		data = Details.objects.filter(class_id=classid)[0:10]
		if len(data) == 0:
			data = byclass(classid=classid, start=3, num=20)

		return render(request, 'snacks.html', {
				'banner': banner_data,
				'menu': menu_data,
				'title': u'美食网 | 小吃大全',
				'data': data,
		})


def Healths(request):

		"""
		饮食健康
		:return:
		"""

		contact_list = Health.objects.order_by('-add_time').all()
		paginator = Paginator(contact_list, 5)
		page = request.GET.get('page')

		if page:
				page = int(page.encode("utf-8"))

		try:
				data = paginator.page(page)
		except PageNotAnInteger:
				# If page is not an integer, deliver first page.
				data = paginator.page(1)
		except EmptyPage:
				# If page is out of range (e.g. 9999), deliver last page of results.
				data = paginator.page(paginator.num_pages)

		if page:
				return render(request, 'health_list.html', {
						'data': data,
				})
		else:
				banner_data = banner()
				menu_data = menu()
				return render(request, 'health.html', {
						'banner': banner_data,
						'menu': menu_data,
						'title': u'美食网 | 饮食健康',
						'data': data,
				})


def Healths_id(request, id):

		"""
		饮食健康内容页
		:return:
		"""

		banner_data = banner()

		# 阅读数增加
		f = Health.objects.get(id=id)
		read_num = int(f.read_num) + 1
		Health.objects.filter(id=id).update(read_num=read_num)

		data = Health.objects.get(id=id)
		menu_data = menu()
		title = data.title

		return render(request, 'health_id.html', {
				'banner': banner_data,
				'menu': menu_data,
				'title': title,
				'data': data,
		})


@cache_page(86400)
def Links(request):

		"""
		友情链接
		:return:
		"""

		banner_data = banner()
		menu_data = menu()
		data = Link.objects.all()

		return render(request, 'link.html', {
				'banner': banner_data,
				'menu': menu_data,
				'title': u'美食网 | 友情链接',
				'data': data,
		})


def page_not_found(request):
		return render(request, '404.html')


def page_error(request):
		return render(request, '404.html')


def permission_denied(request):
		return render(request, '404.html')


def Clear_Cache(request):

		"""
		清理缓存
		:return:
		"""

		# 指定参数删除
		st = request.GET.get('name')
		data = []

		if st == 'clear_file':
				data.append(clear_cache())
				return render(request, 'clear_cache.html', {
						'data': data,
				})

		elif st == 'all':
				data.append(ClassifiCation())
				data.append(like())
				data.append(recommended())
				data.append(Dailys())
				data.append(clear_cache())

				return render(request, 'clear_cache.html', {
						'data': data,
				})

		elif st == 'd':
				data.append(recommended())

				return render(request, 'clear_cache.html', {
						'data': data,
				})
